//
//  WQPictureBrowserController.swift
//  sanwuWeibo
//
//  Created by 王先强 on 15/12/18.
//  Copyright © 2015年 王先强. All rights reserved.
//

import UIKit
import SVProgressHUD
class WQPhotosBrowserController: UIViewController {

    private var selectPhotoIndexPath: NSIndexPath
    private var photoURLs:[NSURL]
    
    //转换将缩略图对url数组转为中等图数组
    
    init(selectIndexPath: NSIndexPath, photoURLs:[NSURL]){
        self.selectPhotoIndexPath = selectIndexPath
        self.photoURLs = photoURLs
//        print(photoURLs)
        super.init(nibName: nil, bundle: nil)
        
        setupUI()
    }
    
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        
        view = UIView(frame: rect)
       
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
         photosView.scrollToItemAtIndexPath(selectPhotoIndexPath, atScrollPosition: .Left, animated: false)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    private lazy var photosView: WQPhotosView = WQPhotosView()

    private lazy var closePhotoButton: UIButton = UIButton(title: "关闭", bgroundColor: UIColor(white: 0.8, alpha: 1.0), fgroundColor: UIColor(white: 0.4, alpha: 1.0), fontSize: 14)
    private lazy var savePhotoButton: UIButton = UIButton(title: "保存", bgroundColor: UIColor(white: 0.8, alpha: 1.0), fgroundColor: UIColor(white: 0.4, alpha: 1.0), fontSize: 14)
    
}

extension WQPhotosBrowserController {
    //collectionView
    private func setupUI() {
        view.addSubview(photosView)
        photosView.dataSource = self
        
        view.addSubview(closePhotoButton)
        view.addSubview(savePhotoButton)
        photosView.frame = view.bounds
        
        closePhotoButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(self.view.snp_left).offset(8)
            make.bottom.equalTo(self.view.snp_bottom).offset(-8)
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        savePhotoButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(self.view.snp_right).offset(-28)
            make.bottom.equalTo(self.view.snp_bottom).offset(-8)
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        
        closePhotoButton.addTarget(self, action: "closeBrowser", forControlEvents: .TouchUpInside)
        savePhotoButton.addTarget(self, action: "savePhoto", forControlEvents: .TouchUpInside)
    }
 
}
// MARK: - 监听方法，photoView手势监听，view上按钮点击时间监听
extension WQPhotosBrowserController: WQPhotosViewCellDelegate {
    func photosViewDidTapImage() {
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    @objc private func closeBrowser() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func savePhoto() {
        let cell = photosView.visibleCells()[0] as! WQPhotosViewCell
        guard let image = cell.photoView.image else {
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, "image:error:contextInfo:", nil)
        
    }
//    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    func image(image: UIImage, error: NSError?, contextInfo: AnyObject){
        
        let message = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(message)
    }
}
// MARK: - WQPhotosBrowserAnimatorDismissDelegate
extension WQPhotosBrowserController: WQPhotosBrowserAnimatorDismissDelegate {
    func imageViewForDismiss() -> UIImageView {
        //创建图片
        let imageView = UIImageView()
        imageView.contentMode = .ScaleAspectFill
        imageView.clipsToBounds = true
        let cell = photosView.visibleCells()[0] as! WQPhotosViewCell
        //将cell中的图片属性赋给imageView
        imageView.image = cell.photoView.image
        imageView.sizeToFit()
        //转换cell.photoView的坐标系为屏幕中
        imageView.frame = cell.photosViewCellScrollView.convertRect(cell.photoView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return imageView
    }
    func indexPathForDismiss() -> NSIndexPath {
        return photosView.indexPathsForVisibleItems()[0]
    }
}

// MARK: - 数据源代理方法
extension WQPhotosBrowserController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoURLs.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WQPhotosViewCellID, forIndexPath: indexPath) as! WQPhotosViewCell
        cell.backgroundColor = randomColor
        cell.photoURL = photoURLs[indexPath.item]
        cell.photoViewDelegate = self
        return cell
    }
    
}